/*
 * XStringEditor.java, created on Nov 12, 2005
 * 
 * Copyright (c) 2005 - 2007
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.xfc.editor;

import java.awt.BorderLayout;

import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 *
 * @author Devon Carew
 */
public class XStringEditor
	extends XEditor
{
	protected JTextField textField;
	
	private DocumentListener documentListener = new DocumentListener()
	{
		public void insertUpdate(DocumentEvent e) { fireEditorEvent(); }
		public void removeUpdate(DocumentEvent e) { fireEditorEvent(); }
		public void changedUpdate(DocumentEvent e) { fireEditorEvent(); }
	};
	
	/**
	 * 
	 */
	public XStringEditor()
	{
		setLayout(new BorderLayout());
		setTextField(new JTextField());
	}
	
	/**
	 * 
	 * 
	 * @param title
	 */
	public XStringEditor(String title)
	{
		this();
		
		setTitle(title);
	}
	
	/**
	 * 
	 * 
	 * @param title
	 * @param columns
	 */
	public XStringEditor(String title, int columns)
	{
		this(title);
		
		getTextField().setColumns(columns);
	}
	
	public Object getValue()
	{
		return getValueAsString();
	}
	
	/**
	 * @return the value of the editor as a String
	 */
	public String getValueAsString()
	{
		String value = textField.getText();
		
		if (value.length() == 0)
			return null;
		
		return value;
	}
	
	public void setValue(Object value)
	{
		if (value == null)
			value = "";
		
		if (!(value instanceof String))
			throw new IllegalArgumentException("value must be a String");
		
		textField.setText((String)value);
		
		setModified(false);
	}

	/**
	 * @return Returns the textField.
	 */
	public JTextField getTextField()
	{
		return textField;
	}
	
	/**
	 * @param textField The textField to set.
	 */
	public void setTextField(JTextField textField)
	{
		if (this.textField != null)
		{
			this.textField.getDocument().removeDocumentListener(documentListener);
			remove(this.textField);
		}
		
		this.textField = textField;
		
		textField.getDocument().addDocumentListener(documentListener);
		textField.setColumns(30);
		
		add(textField, BorderLayout.CENTER);
	}
	
}
